package com.fadadianqi.logistics.admin.controller;

import com.fadadianqi.logistics.admin.controller.form.AjaxResult;
import com.fadadianqi.commons.JSONProvider;
import com.fadadianqi.commons.ParamHelper;
import com.fadadianqi.commons.PrimaryKeyCreator;
import com.fadadianqi.logistics.customer.model.Account;
import com.fadadianqi.logistics.customer.model.Customer;
import com.fadadianqi.logistics.customer.service.AccountService;
import com.fadadianqi.logistics.customer.service.CustomerService;
import com.yeqiangwei.commons.util.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;


/**
 * @author aroot
 */
@Controller
public class AccountController {

    private static final Log log = LogFactory.getLog(AccountController.class);

    @RequestMapping("/a/customer/account/form")
    public String showForm(HttpServletRequest request, ModelMap modelMap) {
        String customerId = ParamUtils.getString(request, "cid", null);
        Customer customer = customerService.getById(customerId);
        modelMap.put("customer", customer);
        String addDate = DateTimeUtils.format(DateTimeUtils.now(), DateTimeUtils.FMT_YYYY_MM_DD);
        modelMap.put("addDate", addDate);
        return "/admin/customer/accountForm";
    }

    /**
     * 帐号充值
     *
     * @param request
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/a/ajax/customer/account/save", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> save(HttpServletRequest request, ModelMap modelMap) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "text/html; charset=utf-8");
        AjaxResult rs = null;
        String customerId = ParamUtils.getString(request, "cid", null);
        Double money = ParamUtils.getDoubleParameter(request, "money");
        String _addDate = DateTimeUtils.format(DateTimeUtils.now(), DateTimeUtils.FMT_YYYY_MM_DD);
        String yyyyMMdd = ParamUtils.getString(request, "addTime", _addDate);
        Date addTime = ParamHelper.getBeginDayTimeByYYYYMMDD(yyyyMMdd);
        Account account = new Account();
        account.setAddTime(addTime);
        account.setCustomerId(customerId);
        account.setId(PrimaryKeyCreator.create());
        account.setUniqueId(customerId);
        account.setMoney(money);
        accountService.create(account);
        rs = new AjaxResult(account, Boolean.TRUE, null);
        return new ResponseEntity<String>(JSONProvider.toJSON(rs),
                responseHeaders, HttpStatus.OK);
    }

    @RequestMapping("/a/ajax/customer/account/record")
    public String record(HttpServletRequest request, ModelMap modelMap) {
        String customerId = ParamUtils.getString(request, "cid", null);
        modelMap.put("customer", customerService.getById(customerId));
        int m = ParamUtils.getInt(request, "m", 100);
        if (m > 1000) {
            m = 1000;
        }
        String pg = ParamUtils.getString(request, "pg", null);// 是否显示分页
        modelMap.put("pg", pg);

        Pagination pagination = new Pagination(request, m);
        List<Account> list = accountService.findByCustomerId(customerId, pagination);
        pagination.setTotal(accountService.countByCustomerId(customerId));

        Map<String, Object> eles = new HashMap<String, Object>();
        eles.put("cid", customerId);
        eles.put("m", m);
        eles.put("pg", pg);
        pagination.setElements(eles);

        modelMap.put("list", list);

        PaginationHelper.setAttribute(request, pagination);

        return "/admin/customer/accountRecord";
    }

    @RequestMapping("/a/ajax/customer/account/search")
    public String search(HttpServletRequest request, ModelMap modelMap) {

        return "/admin/customer/accountSearch";
    }

    /**
     * @param yyyymmhh
     * @param t        0 get year, 1 get month, 2 get date
     * @return
     */
/*	private int parseToYMD(String yyyymmdd, int t) {
        String s = null;
		switch (t) {
		case 0:
			s = StringHelper.substring(yyyymmdd, 0, 4, null);
			break;
		case 1:
			s = StringHelper.substring(yyyymmdd, 5, 7, null);
			break;
		case 2:
			s = StringHelper.substring(yyyymmdd, 8, 10, null);
			break;
		default:
			break;
		}
		return TypeChange.stringToInt(s);
	}*/
    @RequestMapping("/a/customer/account/results")
    public String results(HttpServletRequest request, ModelMap modelMap) {

        //默认显示当月数据
        String btime_ = DateTimeUtils.format(DateTimeUtils.getFirstDayOfMonth(), DateTimeUtils.FMT_YYYY_MM_DD);
        String etime_ = DateTimeUtils.format(DateTimeUtils.getLastDayOfMonth(), DateTimeUtils.FMT_YYYY_MM_DD);

        String _btime = ParamUtils.getString(request, "btime", btime_);
        String _etime = ParamUtils.getString(request, "etime", etime_);

        //Date bday = DateTimeHelper.toDate(_btime, DateTimeUtils.FMT_YYYY_MM_DD);
        //Date eday = DateTimeHelper.toDate(_etime, DateTimeUtils.FMT_YYYY_MM_DD);
        Date btime = ParamHelper.getBeginDayTimeByYYYYMMDD(_btime);
        Date etime = ParamHelper.getEndDayTimeByYYYYMMDD(_etime);

        if (log.isDebugEnabled()) {
            log.debug("/a/customer/account/results, begin:" + btime + ", end:" + etime);
        }

        Pagination pagination = new Pagination(request, 50);
        pagination.setTotal(customerService.countAll());
        List<Customer> list = customerService.findAll(pagination);
        List<CustomerAccount> caList = new ArrayList<CustomerAccount>();
        if (ValidatorHelper.isNotEmpty(list)) {
            for (Customer customer : list) {
                double begin = accountService.getBalanceBegin(customer, btime);
                double end = accountService.getBalanceEnd(customer, etime);
                CustomerAccount ca = new CustomerAccount();
                BeanUtils.copyProperties(ca, customer);
                ca.setBegin(begin);
                ca.setEnd(end);
                caList.add(ca);
            }
        }
        Map<String, Object> eles = new HashMap<String, Object>();
        eles.put("btime", _btime);
        eles.put("etime", _etime);
        pagination.setElements(eles);
        PaginationHelper.setAttribute(request, pagination);
        modelMap.put("caList", caList);
        modelMap.put("b", _btime);
        modelMap.put("e", _etime);
        return "/admin/customer/accountResults";
    }

    @Autowired
    private CustomerService customerService;

    @Autowired
    private AccountService accountService;


    public class CustomerAccount extends Customer {

        /**
         *
         */
        private static final long serialVersionUID = 2532525530556520715L;

        private Double begin; // 期初余额

        private Double end; // 期末余额

        public Double getBegin() {
            return begin;
        }

        public void setBegin(Double begin) {
            this.begin = begin;
        }

        public Double getEnd() {
            return end;
        }

        public void setEnd(Double end) {
            this.end = end;
        }
    }
}
